package db

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"go-web-app-demo/settings"
	"go.uber.org/zap"
)

var DB *sqlx.DB

func Init(cfg *settings.DBConfig) {

	var err error
	driver := cfg.Driver
	dsn := cfg.Dsn
	DB, err = sqlx.Open(driver, dsn)

	if err != nil {
		zap.L().Error("sqlx open err", zap.String("driver", driver), zap.String("dsn", dsn))
		return
	}

	if err = DB.Ping(); err != nil {
		zap.L().Error("sqlx ping err", zap.String("driver", driver), zap.String("dsn", dsn))
		panic(err)
	}

	//maxOpen, maxIdle := 30, 10
	//if viper.InConfig("db.maxOpen") {
	//	maxOpen = viper.GetInt("db.maxOpen")
	//}
	//
	//if viper.InConfig("db.maxIdle") {
	//	maxIdle = viper.GetInt("db.maxIdle")
	//}

	DB.SetMaxOpenConns(int(cfg.MaxOpen))
	DB.SetMaxIdleConns(int(cfg.MaxIdle))

	zap.L().Info("connect DB succeed")

}
